package com.kingwang.demo.springsecuritytokendemo.security;

import com.kingwang.demo.springsecuritytokendemo.utils.HttpServletUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 返回JSON格式认证失败数据的处理器
 *
 * @author King
 */
public class JsonResponseAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        TokenAuthenticationResult result = new TokenAuthenticationResult();
        result.setSuccess(false);
        result.setMessage("认证失败：" + exception.getMessage());

        HttpServletUtils.sendJsonContentResponse(response, HttpStatus.UNAUTHORIZED, result);
    }
}
